// 请求接口
// import getURL from '@/core/api/url';
const Base64 = require('./Base64.js');
require('./hmac.js');
require('./sha1.js');
const Crypto = require('./crypto.js');

// oss上传地址
let fileHost = "https://lgt-test.oss-cn-shanghai.aliyuncs.com"
// if( getURL() === 'https://recruit.lgong.com' ){
//   fileHost = `https://lgt-prod.oss-cn-hangzhou.aliyuncs.com`
// }

// oss上传配置
const envConfig = (config = {}) => {
  return {
    uploadImageUrl: `${fileHost}`, //默认存在根目录，可根据需求改
    AccessKeySecret: config.accessKeySecret,
    OSSAccessKeyId: config.accessKeyId,
    token: config.securityToken,
    timeout: 87600 //这个是上传文件时Policy的失效时间
  }
}

/**
 * 上传图片到阿里云，返回文件名称
 * @param {Object} params 选择chooseImage返回的tempFilePaths，包含 filePath：tempFilePaths[i], dir: "logo"存储文件名称/lgt后面一级,
 */

export function uploadFile(params) {
  return new Promise((resolve, reject) => {
    if (!params.filePath || params.filePath.length < 9) {
      wx.showModal({
        title: '图片错误',
        content: '请重试',
        showCancel: false,
      })
      reject('图片错误');
    }
    getApp().$http.uploadImage().then(res => {
      // 获取到配置，生成相应配置
      console.log('res data::',res)
      const env = envConfig(res);
      const aliyunServerURL = env.uploadImageUrl;
      const accessid = env.OSSAccessKeyId;
      const token = env.token;

      const timestemp = getTimeStemp(); // 时间戳+八位随机数
      const path = params.filePath.replace(/\S+(\.\w+)$/, timestemp + '$1'); // 替换小程序生成的文件名
      const dirPath = `lgt/${params.dir}/`; // 文件存储在oss的文件夹名称
      const aliyunFileKey = dirPath + path; // 完整路径

      const policyBase64 = getPolicyBase64(env);
      const signature = getSignature(policyBase64, env);

      wx.uploadFile({
        url: aliyunServerURL,
        filePath: params.filePath,
        name: 'file',
        formData: {
          'key': `${aliyunFileKey}`,
          'policy': policyBase64,
          'OSSAccessKeyId': accessid,
          'signature': signature,
          'success_action_status': '200',
          'x-oss-security-token': token
        },
        success: function (res) {
          if (res.statusCode != 200) {
            reject(res)
          } else {
            const filePath = `${fileHost}/${aliyunFileKey}`;
            resolve({ aliyunFileKey: filePath, res })
          }
        },
        fail: function (err) {
          err.wxaddinfo = aliyunServerURL;
          reject(err)
        },
      })
    })
  }).catch(err => reject(err))
}

const getPolicyBase64 = function (env) {
  let date = new Date();
  date.setHours(date.getHours() + env.timeout);
  let srcT = date.toISOString();
  const policyText = {
    "expiration": srcT, //设置该Policy的失效时间
    "conditions": [
      ["content-length-range", 0, 5 * 1024 * 1024] // 设置上传文件的大小限制,5mb
    ]
  };

  const policyBase64 = Base64.encode(JSON.stringify(policyText));
  return policyBase64;
}

const getSignature = function (policyBase64, env) {
  const accesskey = env.AccessKeySecret;

  const bytes = Crypto.HMAC(Crypto.SHA1, policyBase64, accesskey, {
    asBytes: true
  });
  const signature = Crypto.util.bytesToBase64(bytes);

  return signature;
}

// 生成时间戳加八位随机数
const getTimeStemp = () => {
  // 生成八位随机数
  const n = 8;
  const re = new RegExp("(\\d{" + n + "})(\\.|$)");
  const num = (Array(n - 1).join(0) + Math.pow(10, n) * Math.random()).match(re)[1];

  // 生成时间戳
  const timestemp = new Date().getTime();

  return `${num}${timestemp}`;
}